import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/auth/viewmodels/login_viewmodel.dart';
import 'package:vista/shared/utils/url_open.dart';
import 'package:vista/shared/utils/widget_extension.dart';

/// 登录页面
class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  final TextEditingController _fullNameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  void dispose() {
    _fullNameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LoginViewModel>.reactive(
      viewModelBuilder: () => LoginViewModel(getIt.get()),
      builder:
          (context, model, child) => Scaffold(
            resizeToAvoidBottomInset: false,
            body: Container(
              decoration: const BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [Color(0xFFFFEBE6), Color(0xFFFFA680)],
                ),
              ),
              child: SafeArea(
                child: [
                  // 返回按钮
                  _buildBackButton(),
                  // 主要内容
                  Expanded(
                    child: [
                          // Logo和名称
                          _buildBrandingSection(),
                          SizedBox(height: 48.h),
                          // 输入框区域
                          _buildInputSection(model),
                          SizedBox(height: 32.h),
                          // 按钮区域
                          _buildActionSection(model),
                          SizedBox(height: 24.h),
                          // 注册链接
                          _buildSignUpLink(),
                          // 弹性空间，推动底部条款到底部
                          const Spacer(),
                          // 底部条款
                          _buildTermsSection(),
                        ]
                        .verticalShot(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                        )
                        .frameHorizontal(24.w),
                  ),
                ].verticalShot().frameAll(0),
              ),
            ),
          ),
    );
  }

  /// 构建返回按钮
  Widget _buildBackButton() {
    return Align(
      alignment: Alignment.topLeft,
      child: IconButton(
        icon: Icon(Icons.chevron_left, color: Colors.black, size: 36.w),
        onPressed: () => getIt<NavigationService>().back(),
      ).frame(top: 8.h, left: 8.w),
    );
  }

  /// 构建品牌标识区域
  Widget _buildBrandingSection() {
    return [
          // Logo
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(
              'assets/images/logo.png',
              width: 80.w,
              height: 80.w,
            ),
          ),
          SizedBox(height: 16.h),
          // 应用名称
          Text(
            'Vista',
            style: GoogleFonts.alegreyaSans(
              fontSize: 28.sp,
              fontWeight: FontWeight.w800,
              color: Colors.black,
              letterSpacing: 1,
            ),
          ),
        ]
        .verticalShot(crossAxisAlignment: CrossAxisAlignment.center)
        .frameVertical(20.h);
  }

  /// 构建输入框区域
  Widget _buildInputSection(LoginViewModel model) {
    return [
      // 全名输入框
      _buildTextField(
        controller: _fullNameController,
        hintText: 'Username',
        obscureText: false,
      ),
      SizedBox(height: 16.h),
      // 密码输入框
      _buildTextField(
        controller: _passwordController,
        hintText: 'Password',
        obscureText: !model.isPasswordVisible,
        suffixIcon: IconButton(
          icon: Icon(
            model.isPasswordVisible ? Icons.visibility : Icons.visibility_off,
            color: Colors.black54,
          ),
          onPressed: model.togglePasswordVisibility,
        ),
      ),
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch);
  }

  /// 构建输入框
  Widget _buildTextField({
    required TextEditingController controller,
    required String hintText,
    required bool obscureText,
    Widget? suffixIcon,
  }) {
    return TextField(
      controller: controller,
      obscureText: obscureText,
      style: TextStyle(fontSize: 16.sp, color: Colors.black87),
      decoration: InputDecoration(
        hintText: hintText,
        hintStyle: TextStyle(color: Colors.grey[400], fontSize: 16.sp),
        filled: true,
        fillColor: const Color(0xFFFFF5F2),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: const BorderSide(color: Colors.black, width: 1),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: const BorderSide(color: Colors.black, width: 1),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: const BorderSide(color: Colors.black, width: 1.5),
        ),
        contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
        suffixIcon: suffixIcon,
      ),
    );
  }

  /// 构建操作按钮区域
  Widget _buildActionSection(LoginViewModel model) {
    return [
      // LOG IN按钮
      _buildLoginButton(model),
      SizedBox(height: 16.h),
      // Sign in with Apple按钮
      _buildAppleSignInButton(model),
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch);
  }

  /// 构建登录按钮
  Widget _buildLoginButton(LoginViewModel model) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFFFA680),
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.black, width: 1),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap:
              model.isBusy
                  ? null
                  : () async {
                    final success = await model.performLogin(
                      account: _fullNameController.text,
                      password: _passwordController.text,
                    );
                    if (success) {
                      getIt<NavigationService>().back();
                    }
                  },
          borderRadius: BorderRadius.circular(8.r),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            alignment: Alignment.center,
            child:
                model.isBusy
                    ? SizedBox(
                      height: 20.h,
                      width: 20.w,
                      child: const CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                    : Text(
                      'LOG IN',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                        letterSpacing: 1,
                      ),
                    ),
          ),
        ),
      ),
    );
  }

  /// 构建Apple登录按钮
  Widget _buildAppleSignInButton(LoginViewModel model) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.black, width: 1),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap:
              model.isBusy
                  ? null
                  : () async {
                    final success = await model.performLoginWithApple();
                    if (success) {
                      getIt<NavigationService>().back();
                    }
                  },
          borderRadius: BorderRadius.circular(8.r),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            alignment: Alignment.center,
            child:
                model.isBusy
                    ? SizedBox(
                      height: 20.h,
                      width: 20.w,
                      child: const CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                      ),
                    )
                    : Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.apple, color: Colors.black, size: 20.sp),
                        SizedBox(width: 8.w),
                        Text(
                          'Sign in with Apple',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
          ),
        ),
      ),
    );
  }

  /// 构建注册链接
  Widget _buildSignUpLink() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          'New User? ',
          style: TextStyle(fontSize: 14.sp, color: Colors.black87),
        ),
        GestureDetector(
          onTap: () {
            getIt<NavigationService>().navigateTo(Routes.register);
          },
          child: Text(
            'Sign Up',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建条款区域
  Widget _buildTermsSection() {
    return Padding(
      padding: EdgeInsets.only(bottom: 32.h),
      child: FittedBox(
        fit: BoxFit.scaleDown,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'By continuing, you agree to our ',
              style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
            ),
            GestureDetector(
              onTap: () {
                UrlOpen.openServiceUrl();
              },
              child: Text(
                'Terms of Service',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.black,
                  decoration: TextDecoration.underline,
                ),
              ),
            ),
            Text(
              ' and ',
              style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
            ),
            GestureDetector(
              onTap: () {
                UrlOpen.openEulaUrl();
              },
              child: Text(
                'EULA',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.black,
                  decoration: TextDecoration.underline,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
